package cn.ezios.huo.system.biz.login;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.ezios.huo.common.mvc.Ret;
import cn.ezios.huo.common.utils.PasswordCall;
import cn.ezios.huo.system.dao.domain.SysUser;
import cn.ezios.huo.system.dao.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class LoginService {

    private final SysUserService userService;

    private final ApplicationEventPublisher eventPublisher;

    /**
     * 根据手机号进行用户校验
     * @param loginAuthData
     * @return
     */
    public Ret loginByPhone(LoginAuthData loginAuthData){
        SysUser user = userService.lambdaQuery()
                .eq(SysUser::getPhone, loginAuthData.getUsername())
                .one();
        return authLogin(loginAuthData, user);
    }
    /**
     * 根据登录名进行校验
     * @param loginAuthData
     * @return
     */
    public Ret loginByLoginName(LoginAuthData loginAuthData){
        SysUser user = userService.lambdaQuery()
                .eq(SysUser::getLoginName, loginAuthData.getUsername())
                .one();
        return authLogin(loginAuthData, user);
    }


    /**
     * 登录校验
     * @param loginAuthData
     * @param user
     * @return
     */
    private Ret authLogin(LoginAuthData loginAuthData, SysUser user) {
        if (user == null) {
            return Ret.error("用户不存在");
        }
        if (!PasswordCall.validatePassword(loginAuthData.getPassword(), user.getPassword())) {
            return Ret.error("密码错误");
        }
        StpUtil.login(user.getUserId(),"TEST-DEV");
        StpUtil.getSession().set("user", user);
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();

        eventPublisher.publishEvent(new LoginEvent(user));
        return Ret.ok().setData(tokenInfo.getTokenValue());
    }

}
